import { reactive, ref, nextTick } from 'vue'
import { initTemp, getTempInfoApi } from 'api/common'
import { extendMapHandle } from 'utils/validate'
import { getTenantInfo } from 'utils/headerToken'
import { priceArr } from 'config/mock'
import { ERR_OK } from 'config/statusCode'
// import { getTableDisplay, headAndSearch, postTableDisplay, putTableDisplay } from '@/hooks/sceneSettings'
import { isObject } from 'utils/validate'
import { download } from 'utils/tools'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
export default function (options) {
  const { getTableDisplay, headAndSearch, postTableDisplay, putTableDisplay } = window.proxy.zcbFun.sceneSettings()
  const { t } = useI18n() // 中英文
  const zcbSearchForm = (options && options.zcbSearchForm) || null //zcb-search
  const tenantInfo = ref({})
  let userInfo = JSON.parse(localStorage.getItem('userinfo'))
  let data = reactive({
    filterColumn: [], // 搜索/模板返回筛选字段
    sceneFilterColumn: [], // 搜索/页面展示的数据（有场景取场景）
    listColumn: [], // 表头/页面展示的数据（有场景取场景）
    defaultColumn: [], //表头原始值
    list: [],
    loading: false,
    sceneList: [],
    tableSetting: {},
    formData: {},
    activeSceneId: '',
    authConfig: {
      'biz-type-code': '',
      'list-config-code': ''
    }
  })
  const comFilterList = ref([])
  let page = reactive({
    current: 1,
    size: 10,
    total: 0
  })
  const sceneVal = ref() // 场景切换值
  const apiFun = ref()
  const otherParams = ref({})
  const lastAction = ref()
  const searchAllVal = ref() //场景为【全部】时使用
  const listFormCode = ref('') // 全局的模版code
  let searchValue = ref({})
  const getSceneDetail = async (docTempCode, id, api) => {
    if (isObject(api)) {
      lastAction.value = api.lastAction || null
      otherParams.value = api.otherParams || {}
      apiFun.value = api.apiFun || ''
    }
    listFormCode.value = docTempCode // 列表模版code
    let sceneFilterInfo = await getheadAndSearch(docTempCode, id)
    // //console.log(sceneFilterInfo)
    sceneFilterInfo.sceneList.unshift({ sceneName: t('keys.all'), id: 0 })
    await getTempList(docTempCode, id)
    let settingList = sceneFilterInfo.settingList && sceneFilterInfo.settingList.length > 0 ? sceneFilterInfo.settingList : []
    let columnList =
      sceneFilterInfo.filterColumn && sceneFilterInfo.filterColumn.columnList && sceneFilterInfo.filterColumn.columnList.length > 0
        ? sceneFilterInfo.filterColumn.columnList
        : []
    let listColumn = !id || lastAction.value ? settingList : columnList
    nextTick(() => {
      // 场景内有搜索和表头数组则取场景内数据，否则取模板数据
      data.activeSceneId = sceneFilterInfo.activeSceneId
      data.tableSetting = sceneFilterInfo.tableSettingInfo
      data.sceneList = sceneFilterInfo.sceneList
      data.formData = sceneFilterInfo.activeSceneId ? sceneFilterInfo.formData : {}
      data.sceneFilterColumn =
        sceneFilterInfo.filterColumn && sceneFilterInfo.filterColumn.filterList && sceneFilterInfo.filterColumn.filterList.length > 0
          ? sceneFilterInfo.filterColumn.filterList
          : data.filterColumn.filter((item) => item.filterFlag)
      data.listColumn = listColumn.length > 0 ? listColumn : data.defaultColumn
      //console.log(data.listColumn)
    })
  }
  // 场景切换searchData.type == 'changeFlag'，其他为场景更新
  const sceneChange = async (val, searchData) => {
    data.loading = true
    sceneVal.value = JSON.stringify(val) !== '{}' ? val.id : 0
    data.formData = {}
    searchAllVal.value = {}
    searchValue.value = {}
    searchData = searchData && JSON.stringify(searchData) !== '{}' ? searchData : {}
    searchValue.value = JSON.stringify(val) !== '{}' ? searchData : {}
    // 场景为全部时使用searchVal
    searchAllVal.value = searchData
    data.formData = Object.assign(data.formData, searchValue.value)
    if (searchData && val.actinType !== 'changeFlag') {
      if (zcbSearchForm.value) {
        zcbSearchForm.value.submitForm('', searchData)
      }
    } else {
      data.list = []
      data.sceneFilterColumn = []
      if (val.isDefaultFlag) {
        await getSceneDetail(listFormCode.value, 0, {
          lastAction: val.lastAction,
          apiFun: apiFun.value,
          otherParams: {
            ...otherParams.value
          }
        })
        sceneVal.value = data.activeSceneId || sceneVal.value
        if (zcbSearchForm.value) {
          zcbSearchForm.value.goInitNum()
        }
        val.isDefaultFlag = null
      } else {
        await getSceneDetail(listFormCode.value, sceneVal.value, {
          lastAction: val.lastAction,
          apiFun: apiFun.value,
          otherParams: {
            ...otherParams.value
          }
        })
      }
      if (zcbSearchForm.value) {
        await zcbSearchForm.value.submitForm('', sceneVal.value ? data.formData : {})
      }
    }
    data.loading = false
  }
  const getTempList = async (docTempCode) => {
    let res = await initTemp(docTempCode)
    if (res.code == ERR_OK) {
      data.authConfig = {
        'biz-type-code': res.data.bizTypeCode,
        'list-config-code': res.data.code
      }
      sortRule.value = [
        {
          asc: res.data.sortTypeCode == 'CREATE_TIME_ASC' || res.data.sortTypeCode == 'UPDATE_TIME_ASC' ? true : false,
          column: res.data.sortTypeCode == 'CREATE_TIME_ASC' || res.data.sortTypeCode == 'CREATE_TIME_DESC' ? 'createdTime' : 'updatedTime'
        }
      ]
      let filterListData = res.data.filterList.map((item) => {
        item.customName = item.fieldName
        item.exposed = true
        if (item.filterFlag) return item
      })
      data.listColumn = []
      filterListData.forEach((v) => {
        v.lovCode = v.formCommonField.lovCode
        v.lovName = v.formCommonField.lovName
        v.lovTypeCode = v.formCommonField.lovTypeCode
        v.presetFlag = v.formCommonField.presetFlag
      })
      nextTick(() => {
        data.filterColumn = filterListData
        data.defaultColumn = res.data.list
      })
    }
  }
  // 获取场景及表头数据
  const getheadAndSearch = async (docTempCode, id) => {
    let data = {
      listFormCode: docTempCode,
      empId: userInfo.empId
    }
    let res = await headAndSearch(data)
    if (res.code == ERR_OK) {
      let tableDisplay = res.data.tableDisplay || {}
      let searchScenarioList = res.data.searchConfigList || []
      let tableHeadConfigList = res.data.tableHeadConfigList || []
      let tableSettingInfo = {}
      tableSettingInfo = tableDisplay.displayJson ? JSON.parse(tableDisplay.displayJson) : {}
      tableSettingInfo.id = tableDisplay.id
      tableSettingInfo.versionNum = tableDisplay.versionNum
      data.tableSetting = tableSettingInfo
      let filterColumn = {}
      let sceneList = []
      let settingList = []
      let formData = {}
      let activeSceneId = 0
      if (searchScenarioList.length > 0) {
        // if (searchType == 'SEARCH_CONFIG') {
        searchScenarioList.forEach((item) => {
          let obj = {}
          obj.id = item.id
          obj.defaultFlag = item.defaultFlag
          obj.sceneName = item.scenarioName
          sceneList.push(obj)
        })
        // }
        // //console.log(searchScenarioList)
        let index = searchScenarioList.findIndex((item) => {
          if (id) {
            return item.id == id
          } else {
            return item.defaultFlag
          }
        })
        //console.log(index)
        if (index > -1) {
          activeSceneId = searchScenarioList[index].id
          if (searchScenarioList[index] && searchScenarioList[index].searchConfig) {
            filterColumn = JSON.parse(searchScenarioList[index].searchConfig)
          }
          if (index > 2) {
            let obj = sceneList[index]
            sceneList.splice(index, 1)
            sceneList.splice(2, 0, obj)
          }
        }
        // else {
        //   if (searchScenarioList[0] && searchScenarioList[0].searchConfig) {
        //     filterColumn = JSON.parse(searchScenarioList[0].searchConfig)
        //   }
        // }
        formData = filterColumn && filterColumn.formData ? filterColumn.formData : {}
      }
      if (tableHeadConfigList && tableHeadConfigList[0] && tableHeadConfigList[0].tableHeadConfig) {
        settingList = JSON.parse(tableHeadConfigList[0].tableHeadConfig)
      }
      return { sceneList, filterColumn, activeSceneId, settingList, formData, tableSettingInfo }
    }
  }
  // 获取表格设置详情
  const getTableSetting = async () => {
    let res = await getTableDisplay({ empId: userInfo.empId })
    if (res.code == ERR_OK) {
      let tableSettingInfo = {}
      tableSettingInfo = JSON.parse(res.data.displayJson)
      tableSettingInfo.id = res.data.id
      tableSettingInfo.versionNum = res.data.versionNum
      data.tableSetting = tableSettingInfo
    }
  }
  // 更新搜索数据变化
  const updateValue = (sceneValInfo, val, filterList) => {
    if (sceneValInfo.id) {
      data.formData = val
      if (filterList || filterList == []) {
        data.sceneFilterColumn = filterList
      }
    } else {
      searchAllVal.value = val
      // 全部场景是否外露处理
      if (filterList || filterList == []) {
        let arr = []
        if (filterList == []) {
          data.filterColumn.forEach((item) => {
            item.exposed = false
          })
        } else {
          filterList.forEach((item) => {
            if (item.exposed) {
              arr.push(item.fieldCode)
            }
          })
          data.filterColumn.forEach((item) => {
            if (arr.includes(item.fieldCode)) {
              item.exposed = true
            } else {
              item.exposed = false
            }
          })
        }
      }
    }
  }
  const sortRule = ref([
    {
      asc: false,
      column: 'createdTime'
    }
  ])
  // 排序
  const sortChange = (column) => {
    sortRule.value = [
      {
        asc: column.order == 'ascending' ? true : false,
        column: column.prop
      }
    ]
    initList()
  }
  const pageChange = ({ size, current }) => {
    page.size = size
    page.current = current
    initList()
  }
  const search = (val) => {
    page.current = 1
    searchValue.value = Object.assign({}, val)
    // 更新搜索值
    // data.formData = Object.assign(searchValue, val)
    initList()
  }
  const initList = async () => {
    data.loading = true
    let apiUrl = apiFun.value ? apiFun.value : options.listFun
    let otherParameters = JSON.stringify(otherParams.value) !== '{}' ? otherParams.value : options.otherParams
    let res = await apiUrl(
      {
        page: page.current,
        size: page.size,
        sorts: sortRule.value,
        ...searchValue.value,
        ...otherParameters
      },
      data.authConfig
    )
    data.list = []
    data.loading = false
    if (res.code == ERR_OK) {
      page.total = res.data.total
      data.list = res.data.list
    }
  }
  // 导出
  let exportLoading = ref(false)
  const exportList = async (apiUrl, templateCode) => {
    let otherParameters = JSON.stringify(otherParams.value) !== '{}' ? otherParams.value : options.otherParams
    exportLoading.value = true
    let res = await apiUrl(
      {
        page: page.current,
        size: page.size,
        sorts: sortRule.value,
        ...searchValue.value,
        ...otherParameters
      },
      templateCode,
      data.authConfig
    )
    exportLoading.value = false
    if (res.code == ERR_OK) {
      download(res.data.url, res.data.object)
      ElMessage({
        showClose: true,
        message: '导出成功',
        type: 'success'
      })
    } else if (res.code == 600) {
      // 导出文件发送至邮件
      ElMessage({
        showClose: true,
        message: res.desc,
        type: 'success'
      })
    }
  }
  // 表单相关布局默认配置参数
  const formOptions = ref({
    span: 8,
    labelPosition: 'left',
    type: 'form',
    width: '140px',
    labelWidth: '130px'
  })
  // 单据栅栏布局排版
  const settingData = ref()
  const versionNum = ref()
  const id = ref()
  const gridClick = (config) => {
    formOptions.value = config
    getOptions()
  }
  const getFormGrid = async () => {
    let res = await getTableDisplay({ empId: userInfo.empId })
    if (res.code == ERR_OK && res.data) {
      settingData.value = res.data.displayJson ? JSON.parse(res.data.displayJson) : {}
      versionNum.value = res.data.versionNum
      id.value = res.data.id
      if (settingData.value.formOptions) {
        formOptions.value = settingData.value.formOptions
      }
    }
  }
  const getOptions = async () => {
    let options = {
      formOptions: formOptions.value
    }
    settingData.value = { ...settingData.value, ...options }
    // 保存全局表格设置
    let info = {
      empId: userInfo.empId,
      displayJson: JSON.stringify(settingData.value)
    }
    let resInfo = !id.value ? await postTableDisplay(info) : await putTableDisplay({ ...info, versionNum: versionNum.value }, id.value)
    if (resInfo.code == ERR_OK) {
      // ElMessage({
      //   message: '布局切换成功',
      //   type: 'success'
      // })
      // emit('confirm')
    }
  }
  const getList = (callback) => {
    tenantInfo.value = getTenantInfo()
    data.loading = true
    callback.then((res) => {
      data.loading = false
      page.total = res.data.total
      data = Object.assign(data, res.data)
      let newList = []
      data.list.map((item) => {
        if (item.currencyInfo) {
          item = handleAmoutData(item, item.currencyInfo)
        }
        if (item['extendMap']) {
          item = { ...item, ...extendMapHandle(item['extendMap'], true) }
        }
        newList.push(item)
        return item
      })
      data.list = newList
    })
  }
  const handleAmoutData = (data, currencyInfo) => {
    let { exchangeTotalPricePrecision, exchangeCurrencySymbol } = currencyInfo
    for (let key in data) {
      let currencySymbol = exchangeCurrencySymbol
      if (key) {
        let cur = data[key]
        // 处理-过滤本位币总金额
        if (priceArr.includes(key) && (cur || cur == 0)) {
          data[key] = currencySymbol
            ? currencySymbol + Number(data[key]).toFixed(exchangeTotalPricePrecision)
            : Number(data[key]).toFixed(exchangeTotalPricePrecision)
        }
      }
    }
    return data
  }
  // 获取单据模板
  const tmpId = ref('')
  const tmpCode = ref('')
  const tmpInfo = ref([])
  const loading = ref(false)
  const getTempInfo = async (tmp) => {
    loading.value = true
    const { code, data } = await getTempInfoApi(tmp, '')
    if (code === ERR_OK) {
      tmpCode.value = data.code
      tmpId.value = data.formTemplateId
      tmpInfo.value = data.formSectionVOList
      loading.value = false
    }
  }
  // 动态ref
  const refFomeList = ref({})
  const setItemRef = (el, key) => {
    if (el) {
      refFomeList.value[key] = el
    }
  }
  // 动态校验所有表单
  const checkFormData = (formValue) => {
    let arr = []
    Object.keys(formValue).map(async (item) => {
      arr.push(refFomeList.value[item]?.validate())
    })
    arr.map((item) => {
      item.then().catch(() => {
        ElMessage({
          message: ' 当前信息有误，请检查！',
          type: 'warning'
        })
        return false
      })
    })
    return Promise.all(arr)
  }
  return {
    checkFormData,
    refFomeList,
    setItemRef,
    tmpCode,
    tmpId,
    tmpInfo,
    getTempInfo,
    getTempList,
    getList,
    getTableSetting,
    getSceneDetail,
    sortChange,
    comFilterList,
    sortRule,
    initList,
    pageChange,
    search,
    sceneVal,
    searchValue,
    searchAllVal,
    updateValue,
    sceneChange,
    gridClick,
    getFormGrid,
    formOptions,
    data,
    page,
    tenantInfo,
    exportList,
    exportLoading
  }
}
